package models

import (
	"github.com/beego/beego/v2/client/orm"
)

type DoProjectOften struct {
	Id           int64         `json:"id"`
	DepartmentId int64         `json:"department_id"`
	ProjectType  string        `json:"project_type"`
	Inventory    *ErpInventory `orm:"rel(fk);null;on_delete(do_nothing)" json:"inventory"`
	Inspects     *Inspects     `orm:"rel(fk);null;on_delete(do_nothing)" json:"inspects"`
	UseNumber    int64         `json:"use_number"`
}

func (a *DoProjectOften) TableName() string {
	return DoProjectOftenTableName()
}

func DoProjectOftenTableName() string {
	return TableName("do_project_often")
}

type DoProjectOftenQueryParam struct {
	BaseQueryParam
	Filter       string `json:"filter"`
	ProjectType  string `json:"project_type"`
	DepartmentId int64  `json:"department_id"`
}

//获取常用项目
func DoProjectOftenPageList(param *DoProjectOftenQueryParam) []*DoProjectOften {
	var query orm.QuerySeter
	if param.ProjectType == "drug" {
		query = orm.NewOrm().QueryTable(DoProjectOftenTableName()).RelatedSel("Inventory", "Inventory__Products")
		query = query.Filter("Inventory__Inventory__gt", 0)
	} else {
		query = orm.NewOrm().QueryTable(DoProjectOftenTableName()).RelatedSel("Inspects")
		query = query.Filter("Inspects__IsStop", 0)
	}
	data := make([]*DoProjectOften, 0)
	query = query.Filter("DepartmentId", param.DepartmentId)
	query.OrderBy("-use_number").Limit(100).All(&data)
	return data
}

//保存项目
func DoProjectOftenSave(model *DoProjectOften) error {
	o := orm.NewOrm()
	finq := o.QueryTable(DoProjectOftenTableName())
	finq = finq.Filter("department_id", model.DepartmentId)
	finq = finq.Filter("project_type", model.ProjectType)
	cond := orm.NewCondition()
	cond1 := orm.NewCondition()
	cond = cond.AndCond(cond1.Or("inventory_id", model.Inventory.Id).Or("inspects_id", model.Inspects.Id))
	newModel := new(DoProjectOften)
	finq.SetCond(cond).One(newModel)
	if newModel.Id > 0 { //判断是否存在
		newModel.UseNumber += 1
		if _, err := o.Update(newModel, "use_number"); err != nil {
			return nil
		}
	} else {
		model.UseNumber = 1
		if _, err := o.Insert(model); err != nil { //新增
			return err
		}
	}
	return nil
}
